package com.tplan.tplanrabbitmqserver.config;

import com.tplan.constants.EmailConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import java.util.Properties;

@Configuration
public class MailConfig {
    @Autowired
    private Environment env;

    @Bean(name = "JavaMailSender")
    public JavaMailSender getSender() {
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setUsername(env.getProperty(EmailConstants.EMAIL_FROM));
        javaMailSender.setPassword(env.getProperty(EmailConstants.EMAIL_FROM_PASSWORD));
        javaMailSender.setHost(env.getProperty(EmailConstants.EMAIL_HOST));
        javaMailSender.setPort(Integer.parseInt(env.getProperty(EmailConstants.EMAIL_PORT)));
        javaMailSender.setDefaultEncoding(EmailConstants.ENCODE_UTF_8);
        Properties properties = new Properties();
        properties.setProperty(EmailConstants.MAIL_SMTP_HOST, env.getProperty(EmailConstants.EMAIL_HOST));
        properties.setProperty(EmailConstants.MAIL_SMTP_AUTH, env.getProperty(EmailConstants.EMAIL_SMTP_AUTH));
        javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(env.getProperty(EmailConstants.EMAIL_FROM), env.getProperty(EmailConstants.EMAIL_FROM_PASSWORD));
            }
        });
        javaMailSender.setSession(session);
        return javaMailSender;
    }
}
